package com.jiawa.train.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiawa.train.business.domain.po.DailyTrainSeat;
import com.jiawa.train.business.domain.po.TrainSeat;
import com.jiawa.train.business.domain.po.TrainStation;
import com.jiawa.train.business.mapper.DailyTrainSeatMapper;
import com.jiawa.train.business.req.DailyTrainSeatQueryReq;
import com.jiawa.train.business.req.DailyTrainSeatSaveReq;
import com.jiawa.train.business.resp.DailyTrainSeatQueryResp;
import com.jiawa.train.business.service.IDailyTrainSeatService;
import com.jiawa.train.business.service.ITrainSeatService;
import com.jiawa.train.business.service.ITrainStationService;
import com.jiawa.train.common.exception.BusinessException;
import com.jiawa.train.common.exception.BusinessExceptionEnum;
import com.jiawa.train.common.resp.PageResp;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 每日座位 服务实现类
 * </p>
 *
 * @author hrz
 * @since 2025-09-07
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DailyTrainSeatServiceImpl extends ServiceImpl<DailyTrainSeatMapper, DailyTrainSeat> implements IDailyTrainSeatService {

    
    private final ITrainSeatService trainSeatService;
    private final ITrainStationService trainStationService;
    
    @Override
    public PageResp<DailyTrainSeatQueryResp> queryList(DailyTrainSeatQueryReq req) {
        Page<DailyTrainSeat> page = this.lambdaQuery()
                .eq(req.getTrainCode()!=null,DailyTrainSeat::getTrainCode, req.getTrainCode())
                .orderByAsc(req.getTrainCode()!=null,DailyTrainSeat::getTrainCode)
                .page(new Page<>(req.getPage(), req.getSize()));
        List<DailyTrainSeat> records = page.getRecords();
        if(ObjectUtil.isEmpty(records)){
            PageResp<DailyTrainSeatQueryResp> r = new PageResp<>();
            r.setList(new ArrayList<>());
            r.setTotal(0L);
            return r;
        }
        List<DailyTrainSeatQueryResp> respList = BeanUtil.copyToList(records, DailyTrainSeatQueryResp.class);
        PageResp<DailyTrainSeatQueryResp> r = new PageResp<>();
        r.setList(respList);
        r.setTotal(page.getTotal());
        return r;
    }

    @Override
    public void delete(Long id) {
        if(ObjectUtil.isEmpty(id)){
            throw new BusinessException(BusinessExceptionEnum.ID_NULL);
        }
        this.removeById(id);
    }

    @Override
    public void saveDailyTrainSeat(DailyTrainSeatSaveReq req) {
        //2.判断是否是更新
        DailyTrainSeat dailyTrainSeat = BeanUtil
                .copyProperties(req, DailyTrainSeat.class);
        if(ObjectUtil.isNotEmpty(req.getId())){
            //更新
            dailyTrainSeat.setUpdateTime(LocalDateTime.now());
            this.updateById(dailyTrainSeat);
        }else{
            //新增
            //1.唯一性确认
            DailyTrainSeat one = this.lambdaQuery()
                    .eq(DailyTrainSeat::getCol, req.getCol())
                    .eq(DailyTrainSeat::getRow, req.getRow())
                    .eq(DailyTrainSeat::getDate, req.getDate())
                    .one();
            if (ObjectUtil.isNotEmpty(one)|| one != null ) {
                throw new BusinessException(BusinessExceptionEnum.BUSINESS_DAILY_TRAIN_SEAT_UNIQUE_ERROR);
            }
            dailyTrainSeat.setCreateTime(LocalDateTime.now());
            dailyTrainSeat.setUpdateTime(LocalDateTime.now());
            this.save(dailyTrainSeat);
        }
    }

    @Override
    public void genDaily(Date date, String code) {
        //1.删除旧数据
        this.lambdaUpdate()
                .eq(DailyTrainSeat::getDate, date)
                .eq(DailyTrainSeat::getTrainCode, code)
                .remove();
        //2.查询改车次的所有车座
        List<TrainSeat> list = trainSeatService.lambdaQuery()
                .eq(TrainSeat::getTrainCode, code)
                .orderByAsc(TrainSeat::getRow)
                .orderByAsc(TrainSeat::getCol)
                .list();
        if (ObjectUtil.isEmpty(list)) {
            log.info("该车次没有车座");
            return;
        }
        //查询出该车次共有几个车站,方便下面的设置售卖
        Long count = trainStationService.lambdaQuery()
                .eq(TrainStation::getTrainCode, code)
                .count();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < count; i++) {
            sb.append("0");
        }
        String sell = sb.toString();
        //3.生成数据并持久化
        for (TrainSeat seat : list) {
            DailyTrainSeat dailyTrainSeat = BeanUtil.copyProperties(seat, DailyTrainSeat.class);
            dailyTrainSeat.setId(null);
            dailyTrainSeat.setDate(date);
            dailyTrainSeat.setCreateTime(LocalDateTime.now());
            dailyTrainSeat.setUpdateTime(LocalDateTime.now());
            dailyTrainSeat.setSell(sell);
            this.save(dailyTrainSeat);
        }

    }

    @Override
    public int countSeat(Date date, String trainCode) {
        Long count = this.lambdaQuery()
                .eq(DailyTrainSeat::getDate, date)
                .eq(DailyTrainSeat::getTrainCode, trainCode)
                .count();
        return count == null ? 0 : count.intValue();
    }
}
